// 上传功能实现
$(document).ready(function() {
    const dropZone = $('#uploadDropZone');
    const fileInput = $('#fileInput');
    const progressContainer = $('#uploadProgressContainer');
    const progressBar = $('#uploadProgressBar');
    const statusText = $('#uploadStatusText');

    // 拖放功能
    dropZone.on('dragover', function(e) {
        e.preventDefault();
        dropZone.addClass('dragover');
    });

    dropZone.on('dragleave', function(e) {
        e.preventDefault();
        dropZone.removeClass('dragover');
    });

    dropZone.on('drop', function(e) {
        e.preventDefault();
        dropZone.removeClass('dragover');
        if (e.originalEvent.dataTransfer.files.length > 0) {
            handleFiles(e.originalEvent.dataTransfer.files);
        }
    });

    // 文件选择处理
    fileInput.on('change', function(e) {
        if (e.target.files.length > 0) {
            handleFiles(e.target.files);
        }
    });
});

// 处理文件上传
function handleFiles(files) {
    const progressContainer = $('#uploadProgressContainer');
    const progressBar = $('#uploadProgressBar');
    const statusText = $('#uploadStatusText');

    // 显示进度条
    progressContainer.removeClass('d-none');
    progressBar.css('width', '0%');
    statusText.text(`准备上传 ${files.length} 个文件...`);

    // 逐个上传文件
    Array.from(files).forEach((file, index) => {
        uploadFile(file, index + 1, files.length);
    });
}

// 实际上传函数
function uploadFile(file, currentIndex, totalFiles) {
    const formData = new FormData();
    formData.append('file', file);

    const progressBar = $('#uploadProgressBar');
    const statusText = $('#uploadStatusText');

    const xhr = new XMLHttpRequest();

    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            const percent = Math.round((e.loaded / e.total) * 100);
            progressBar.css('width', percent + '%');
            statusText.text(`上传中: ${file.name} (${percent}%)`);
        }
    };

    xhr.onload = function() {
        if (xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
                // 添加到上传历史
                addToUploadHistory(file.name, response.data || '上传成功');

                if (currentIndex === totalFiles) {
                    statusText.html('<span class="text-success">所有文件上传完成!</span>');
                    // 2秒后重置
                    setTimeout(() => {
                        progressBar.css('width', '0%');
                        $('#fileInput').val('');
                    }, 2000);
                }
            } else {
                statusText.html(`<span class="text-danger">${file.name} 上传失败: ${response.message}</span>`);
            }
        } else {
            statusText.html(`<span class="text-danger">${file.name} 上传出错: ${xhr.statusText}</span>`);
        }
    };

    xhr.onerror = function() {
        statusText.html(`<span class="text-danger">${file.name} 上传出错: ${xhr.statusText}</span>`);
    };

    xhr.open('POST', `${Config.API_URL}/upload`, true);
    xhr.send(formData);
}

// 添加上传历史记录（可选）
function addToUploadHistory(filename, message) {
    const historyList = $('#uploadHistory');
    const timestamp = new Date().toLocaleTimeString();

    historyList.prepend(`
        <li class="list-group-item d-flex justify-content-between align-items-center">
            <span>${filename}</span>
            <span class="badge bg-success rounded-pill">${message}</span>
            <small class="text-muted">${timestamp}</small>
        </li>
    `);

    // 限制历史记录数量
    if (historyList.children().length > 5) {
        historyList.children().last().remove();
    }
}